package O2_Selection_Sort;

/**
 * Created by Choisaaaa on 2018/6/4.
 *
 */
public class SelectionSort {
    private SelectionSort(){}

    public static void  sort(Comparable[] arr){
        int length = arr.length;
        for(int i = 0 ;i < length ;i++){//寻找[i,n)区间的最小值
            int minIndex = i;//记录最小元素的下标
            for (int j = i+1; j < length; j++){
                if(arr[j].compareTo(arr[minIndex]) < 0){//使用compareTo比较两个Comparable对象的大小
                    minIndex = j;
                }
                swap(arr,i,minIndex);
            }
        }

    }

    private static void swap(Object[] arr, int i, int minIndex) {
        Object temp  = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }

    public static void main(String[] args){
        // 测试Integer
        Integer[] a = {10,9,8,7,6,5,4,3,2,1};
        SelectionSort.sort(a);
        for( int i = 0 ; i < a.length ; i ++ ){
            System.out.print(a[i]);
            System.out.print(' ');
        }
        System.out.println();

        // 测试Double
        Double[] b = {4.4, 3.3, 2.2, 1.1};
        SelectionSort.sort(b);
        for( int i = 0 ; i < b.length ; i ++ ){
            System.out.print(b[i]);
            System.out.print(' ');
        }
        System.out.println();

        // 测试String
        String[] c = {"D", "C", "B", "A"};
        SelectionSort.sort(c);
        for( int i = 0 ; i < c.length ; i ++ ){
            System.out.print(c[i]);
            System.out.print(' ');
        }
        System.out.println();

        // 测试自定义的类 Student
        Student[] d = new Student[4];
        d[0] = new Student("D",90);
        d[1] = new Student("C",100);
        d[2] = new Student("B",95);
        d[3] = new Student("A",95);
        SelectionSort.sort(d);
        for( int i = 0 ; i < d.length ; i ++ )
            System.out.println(d[i]);

    }
}
